package edu.tjut.tjutcommunity.utils;


import com.alibaba.fastjson.JSON;
import edu.tjut.tjutcommunity.entity.NoticeMessage;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MessageQueueUtils {

    final
    RedisStream redisStream;

    public MessageQueueUtils(RedisStream redisStream) {
        this.redisStream = redisStream;
    }

    public Boolean deleteMessageById(String stuId,String... messageIds){
        return redisStream.deleteMessageById(stuId+"_mq",messageIds);
    }
    public Boolean clearMessageQueue(String stuId){
        return redisStream.deleteStream(stuId+"_mq");
    }

    //发送文本消息
    public void sendText(String stuId,String text){
        SessionPool.sendMessage(stuId, text);
    }


    //发送消息
    public boolean sendMessage(String stuId, NoticeMessage... message) {
        try {
            //加入消息队列缓存
            String mqName = stuId + "_mq";
            redisStream.trim(mqName, 1000L);
            Arrays.stream(message).forEach(m -> {
                String body = JSON.toJSONString(m);
                String messageId = redisStream.add(mqName, "msg", body);
                m.setMessageId(messageId);
            });
            //如果用户在线，直接发送消息
            if (SessionPool.sessions.containsKey(stuId)) {
                try {
                    SessionPool.sendMessage(stuId, JSON.toJSONString(Collections.singletonMap("msg", message)));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public List<NoticeMessage> readMessage(String stuId, String messageId) {
        String key = stuId + "_mq";
        List<MapRecord<String, Object, Object>> records = redisStream.read(key, messageId);
        return records.stream().map(record -> {
            NoticeMessage message = JSON.parseObject(record.getValue().get("msg").toString(), NoticeMessage.class);
            message.setMessageId(record.getId().toString());
            return message;
        }).collect(Collectors.toList());
    }
    public static boolean checkMessageId(String messageId) {
        String[] split = messageId.split("-");
        if(split.length!=2) return false;
        try {
            Long.parseLong(split[0]);
            Long.parseLong(split[1]);
        }catch (Exception e){
            return false;
        }
        return true;
    }
}
